// 访问权限拦截
import router from '@/router'
import store from '@/store'
// nprogress是一个轻量级的进度条组件
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
// 关闭加载的小圆圈动画
NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/404']
// 前置守卫
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      // 每进一个页面就会发一次请求，这样不合理
      // 重复请求 -》优化
      if (!store.state.user.userInfo.userId) {
        const res = await store.dispatch('user/getUserInfo')
        console.log('未来做权限控制需要用到的数据', res)
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 后置守卫
router.afterEach((to, from) => {
  NProgress.done()
})
